<template>
  <div class="home">
    <div class="show-area">
      <div class="msg-item" v-for="(item, index) in messageList" :key="index">
        <div>{{ dateTime(item.timestamp) }}</div>
        <div>
          <span>{{ item.userName }}：</span>
          <span>{{ item.content }}</span>
        </div>
      </div>
    </div>

    <div class="input-area">
      <input
        type="text"
        placeholder="请输入你要发送的消息"
        v-model="content"
        @keydown="handleKeyDown"
      />
      <button @click="handleSendMessage">发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",

  data() {
    return {
      websocket: null,
      storage: localStorage,
      messageList: [],
      content: "",
      userName: "",
    };
  },

  computed: {
    // 时间转换
    dateTime() {
      return (timestamp) => {
        return new Date(parseInt(timestamp))
          .toLocaleString()
          .replace(/:\d{1,2}$/, " ");
      };
    },
  },

  created() {
    console.log("created 1");
    this.autoExit();
    this.websocket = new WebSocket("ws://localhost:8000");
    this.bindEvent();
  },

  // 页面组件销毁时
  destroyed() {
    // 移除监听事件以及创建的 WebSocket 实例
    console.log("destroy");
    this.websocket.removeEventListener("open", this.handleOpen, false);
    this.websocket.removeEventListener("close", this.handleClose, false);
    this.websocket.removeEventListener("error", this.handleError, false);
    this.websocket.removeEventListener("message", this.handleMessage, false);
    this.websocket = null;
  },

  methods: {
    // 绑定事件
    bindEvent() {
      if (this.websocket) {
        this.websocket.addEventListener("open", this.handleOpen, false);
        this.websocket.addEventListener("close", this.handleClose, false);
        this.websocket.addEventListener("error", this.handleError, false);
        this.websocket.addEventListener("message", this.handleMessage, false);
      } else {
        alert("WebSocket 对象实例化失败");
      }
    },

    // 处理键盘事件
    handleKeyDown(event) {
      // console.log(event);
      if (event.key === "Enter") {
        this.handleSendMessage();
      }
    },
    // 处理发送消息
    handleSendMessage() {
      const content = this.content.trim();
      if (!content) {
        alert("消息发送不能为空哦~");
        return;
      }
      const payload = {
        userName: this.userName,
        content: this.content,
        timestamp: +new Date(),
      };
      this.websocket.send(JSON.stringify(payload));
      this.content = "";
    },

    handleOpen(event) {
      console.log(event);
    },

    handleClose(event) {
      console.log(event);
    },

    handleError(event) {
      console.log(event);
    },

    handleMessage(event) {
      console.log(event);
      const data = JSON.parse(event.data);
      this.messageList.push(data);
    },

    // 自动退出，去登陆
    autoExit() {
      this.userName = this.storage.getItem("userName");
      if (!this.userName) {
        this.gotoLogin();
      }
    },

    gotoLogin() {
      this.$router.push("/");
    },
  },
};
</script>

<style>
.home .show-area .msg-item {
  margin-bottom: 10px;
}
</style>